package com.liam.leetcode;


import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

public class 最长回文子串_5 {

    public static void main(String[] args) {
        long begin = System.currentTimeMillis();
        String str = "babadada";
        str = "civilwartestingwhetherthatnaptionoranynartionsoconceivedandsodedicatedcanlongendureWeareqmetonagreatbattlefiemldoftzhatwarWehavecometodedicpateaportionofthatfieldasafinalrestingplaceforthosewhoheregavetheirlivesthatthatnationmightliveItisaltogetherfangandproperthatweshoulddothisButinalargersensewecannotdedicatewecannotconsecratewecannothallowthisgroundThebravelmenlivinganddeadwhostruggledherehaveconsecrateditfaraboveourpoorponwertoaddordetractTgheworldadswfilllittlenotlenorlongrememberwhatwesayherebutitcanneverforgetwhattheydidhereItisforusthelivingrathertobededicatedheretotheulnfinishedworkwhichtheywhofoughtherehavethusfarsonoblyadvancedItisratherforustobeherededicatedtothegreattdafskremainingbeforeusthatfromthesehonoreddeadwetakeincreaseddevotiontothatcauseforwhichtheygavethelastpfullmeasureofdevotionthatweherehighlyresolvethatthesedeadshallnothavediedinvainthatthisnationunsderGodshallhaveanewbirthoffreedomandthatgovernmentofthepeoplebythepeopleforthepeopleshallnotperishfromtheearth";
        System.out.println(longestPalindrome(str));

        System.out.println(System.currentTimeMillis() - begin);
    }

    public static String longestPalindrome(String str) {
        if (str.length() <= 1) {
            return str;
        }

        int maxLen = 1;
        int begin = 0;
        char[] chars = str.toCharArray();

        for (int i = 0; i < str.length() - 1; i++) {
            for (int j = i + 1; j < str.length(); j++) {

                if ((j - i + 1 > maxLen) && isResult3(chars, i, j)) {
                    maxLen = j - i + 1;
                    begin = i;
                }

            }
        }
        return str.substring(begin, begin + maxLen);
    }


    public static boolean isResult3(char[] charArray, int left, int right) {
        while (left < right) {
            if (charArray[left] != charArray[right]) {
                return false;
            }
            left++;
            right--;
        }
        return true;
    }


    /**
     * 这种方式 效率比 stringbuffer 高
     * @param str
     * @return
     */
    public static boolean isResult2(String str) {
        for (int i = 0; i < str.length() / 2; i++) {
            if (str.charAt(i) != str.charAt(str.length() -1 - i)) {
                return false;
            }
        }
        return true;
    }
    private static boolean isResult(StringBuffer sb) {
        String temp = sb.toString();
        if (temp.equals(sb.reverse().toString())) {
            return true;
        }
        return false;
    }


}
